const _ = require('lodash')
const fp = require('lodash/fp')

/**
 * 第一大题
 */
new Promise(resolve => {
  resolve('hello')
}).then(res => {
  return new Promise(resolve => {
    resolve(res + ' lagou')
  })
}).then(res => {
  return new Promise(resolve => {
    resolve(res + ' I love you')
  })
}).then(console.log)


/**
 * 第二大题
 */

// 练习1
const cars = [{name: 'BMW-1', dollar_value: 300000, in_stock: true},{name: 'BMW-7', dollar_value: 500000, in_stock: true}]
let isLastInStock = fp.flowRight(fp.prop('in_stock'), fp.last)
isLastInStock(cars)

// 练习2
let getFirstCarName =fp.flowRight(fp.prop('name'), fp.first)
getFirstCarName(cars)

// 练习3
let _average = function(xs) {
  return fp.reduce(fp.add, 0, xs) / xs.length
}
let averageDollarValue = fp.flowRight(_average, fp.map(function(car) {
  return car.dollar_value
}));
averageDollarValue(cars)

// 练习4
let arr = ['Hello World']
let _underscore = fp.replace(/\W+/g, '_')
let sanitizeNames = fp.map(_.flowRight(fp.toLower ,_underscore))
sanitizeNames(arr)


/**
 * 第三大题
 */

 // 练习1
let ex1 = () => {
  return maybe.map(val => {
    // 值都增加1（不知道有没有理解错题意...）
    return fp.map(fp.add(1), val)
  })
}

// 练习2
let ex2 = () => {
  return xs.map(x => fp.first(x))
}

// 练习3
let ex3 = () => {
  return saveProp('name')(user).map(x => fp.first(x))
}

// 练习4
let ex4 = () => {
  return Maybe.of(n).map(parent)
}


/**
 * 第四大题
 */
const FUFILLED = 'fufilled';
const REJECTED = 'rejected';
const PENDING = 'pending';

class MyPromise {
  constructor(executor) {
    try {
      executor(this.resolve, this.reject);
    } catch (e) {
      this.reject(e);
    }
  }

  //初始状态
  status = PENDING;
  //resolve传入的值
  value = undefined;
  //reject传入的原因
  reason = undefined;
  //成功回调
  successCallbacks = [];
  //失败回调
  failCallbacks = [];

  resolve = (value) => {
    //如果当前状态不是pending（已更改），直接返回
    if (this.status !== PENDING) return;
    this.status = FUFILLED;
    this.value = value;
    //如果成功回调队列有值，依次执行回调
    while (this.successCallbacks.length) this.successCallbacks.shift()();
  };

  reject = (reason) => {
    //如果当前状态不是pending（已更改），直接返回
    if (this.status !== PENDING) return;
    this.status = REJECTED;
    this.reason = reason;
    //如果失败回调队列有值，依次执行回调
    while (this.failCallbacks.length) this.failCallbacks.shift()();
  };

  then(successCallback, failCallback) {
    //将then方法的参数变成可选参数
    successCallback = successCallback ? successCallback : value => value;
    failCallback = failCallback ? failCallback : reason => { throw reason; };
    const _promise = new MyPromise((resolve, reject) => {
      //判断状态
      if (this.status === FUFILLED) {
        setTimeout(() => {
          try {
            const x = successCallback(this.value);
            resolvePromise(_promise, x, resolve, reject);
          } catch (e) {
            reject(e);
          }
        }, 0);
      } else if (this.status === REJECTED) {
        setTimeout(() => {
          try {
            const x = failCallback(this.reason);
            resolvePromise(_promise, x, resolve, reject);
          } catch (e) {
            reject(e);
          }
        }, 0);
      } else {
        //异步代码，需要将回调函数保存至队列
        this.successCallbacks.push(() => {
          setTimeout(() => {
            try {
              const x = successCallback(this.value);
              resolvePromise(_promise, x, resolve, reject);
            } catch (e) {
              reject(e);
            }
          }, 0);
        });
        this.failCallbacks.push(() => {
          setTimeout(() => {
            try {
              const x = failCallback(this.reason);
              resolvePromise(_promise, x, resolve, reject);
            } catch (e) {
              reject(e);
            }
          }, 0);
        });
      }
    });
    return _promise;
  }

  finally(callback) {
    return this.then(value => {
      return MyPromise.resolve(callback()).then(() => value)
    }, reason => {
      return MyPromise.resolve(callback()).then(() => { throw reason })
    })
  }

  catch(failCallback) {
    return this.then(undefined, failCallback);
  }

  static all(array) {
    const result = [];
    let index = 0;
    return new MyPromise((resolve, reject) => {
      function addData(key, value) {
        index++;
        result[key] = value;
        if (index === array.length) resolve(result);
      }
      for (let i = 0; i < array.length; i++) {
        const x = array[i];
        if (x instanceof MyPromise) {
          x.then(
            (res) => {
              addData(i, res);
            },
            (reason) => {
              reject(reason);
            }
          );
        } else {
          addData(i, array[i]);
        }
      }
    });
  }

  static resolve(value) {
    if (value instanceof MyPromise) return value;
    return new MyPromise(resolve => {
      resolve(value);
    })
  }
}

function resolvePromise(_promise, x, resolve, reject) {
  //如果_promise和x相同，则说明发生了循环调用
  if (_promise === x) {
    return reject(new TypeError('Chaining cycle detected for promise #<Promise>'));
  }
  //如果x是MyPromise的实例，根据x的返回结果调用resolve或者reject，否则直接调用resolve
  if (x instanceof MyPromise) {
    x.then(resolve, reject);
  } else {
    resolve(x);
  }
}

module.exports = MyPromise;
